import React from 'react';
import {connect} from 'dva';
import {
	Form,
	Row,
	Col,
	Button,
	Divider,
	message
} from 'antd';
import {routerRedux} from 'dva/router';
import {fetchGet} from '../../../utils/utils';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/braft.css';
import config from '../../../config';
import host from '../../../services/host';

// 该功能使用的富文本编辑器的文档
// 文档 https://github.com/margox/braft-editor/blob/master/README.md

@Form.create()
class Step2 extends React.PureComponent {
	state = {
		content: '',
		contentLength: 0,
		// 已经上传的了图片
		uploadImages: [],
		// 需要确认的图片，只有确认了的才是真正上传成功的，不然一段时间后会再服务器删除掉，导致链接失效
		needConfirmImages: []
	};
	componentDidMount() {
		// 先生成一个上传的accessToken
		this.fetchUploadAccessToken();
		this.initContent();
	};

	setLocalStorage = () => {
		// 设置storeage是为了防止不小心刷新页面导致数据丢失
		localStorage.setItem('content', this.state.content);
		localStorage.setItem('contentLength', this.state.contentLength);
	};

	// 避免直接点下一步的时候报内容为空
	initContent = () => {
		this.setState({
			content: this.editorInstance.getHTMLContent(),
			// 需要把html标签去掉，没有过滤图片和链接，所以内容里面不能只上传图片
			contentLength: this.editorInstance.getHTMLContent().replace(/<[^>]+>/g, '').length
		});
	};

	handleHTMLChange = content => {
		this.setState({
			content,
			contentLength: content.replace(/<[^>]+>/g, '').length
		});
		this.setLocalStorage();
	};

	handelSave = () => {
		const {data, dispatch} = this.props;
		// 提交服务器成功后需要将一部分storage清空
		// 比如uploadImages和needConfirmImages
		dispatch({
			type: 'article/submitStepForm',
			payload: {
				...data,
				...this.state
			}
		});
	};

	fetchUploadAccessToken = () => {
		this.props.dispatch({type: 'upload/fetchAccessToken'});
	};
	handelUploadFn = param => {
		const myThis = this;
		const {uploadAccessToken} = myThis.props;

		const serverURL = config.upload_server_url;
		const xhr = new XMLHttpRequest();
		const fd = new FormData();
		fd.append('accessToken', uploadAccessToken);
		const successFn = response => {
			console.log(response);
			// 假设服务端直接返回文件上传后的地址
			// 上传成功后调用param.success并传入上传后的文件地址
			const result = JSON.parse(xhr.response);
			if (result.code !== 0) {
				param.error({msg: result.message});
				// 再次获取一个上传的token
				this.fetchUploadAccessToken();
			} else {
				myThis.setState({
					uploadImages: [
						...myThis.state.uploadImages, {
							url: result.data.files.file.url,
							upload_access_token: uploadAccessToken
						}
					]
				});
				param.success({url: result.data.files.file.url});
			}
		};

		const progressFn = event => {
			// 上传进度发生变化时调用param.progress
			param.progress(event.loaded / event.total * 100);
		};

		const errorFn = response => {
			// 上传发生错误时调用param.error
			console.log(response);
			param.error({msg: 'unable to upload.'});
		};

		xhr.upload.addEventListener('progress', progressFn, false);
		xhr.addEventListener('load', successFn, false);
		xhr.addEventListener('error', errorFn, false);
		xhr.addEventListener('abort', errorFn, false);

		fd.append('file', param.file);
		xhr.open('POST', serverURL, true);
		xhr.send(fd);
	};
	handelMediaInsert = (fileList) => {
		const {needConfirmImages, uploadImages} = this.state;
		const filterUploadImages = uploadImages;
		// needConfirmImages 使用的图片
		// uploadImages 所有上传的图片
		// filterUploadImages 未使用的图片
		for (let i = 0; i < fileList.length; i++) {
			for (let j = 0; j < uploadImages.length; j++) {
				if (fileList[i].url === uploadImages[j].url) {
					needConfirmImages.push(uploadImages[j]);
					filterUploadImages.splice(j, 1);
				}
			}
		}

		this.setState({uploadImages: filterUploadImages, needConfirmImages});
	};
	render() {
		const {data, dispatch, submitting} = this.props;
		const onPrev = () => {
			dispatch(routerRedux.push(`/article/pub-article/info?id=${data.id}`));
		};
		const onValidateForm = e => {
			if (this.state.contentLength === 0) {
				message.error('文章内容不能为空');
			} else {
				dispatch({
					type: 'article/submitStepForm',
					payload: {
						...data,
						...this.state
					}
				});
				dispatch(routerRedux.push(`/article/pub-article/setCover?id=${data.id}`));
			}
		};
		const editorProps = {
			placeholder: '在这里输入文章内容',
			contentFormat: 'html',
			initialContent: data.content,
			tabIndents: 4,
			onHTMLChange: this.handleHTMLChange,
			onSave: this.handelSave,
			viewWrapper: '.wrapper',
			media: {
				allowPasteImage: true,
				image: true,
				validateFn: null,
				uploadFn: this.handelUploadFn,
				onInsert: this.handelMediaInsert
			}
		};

		return (<div>
			<Row>
				{/* <Col span={6}>
					<div>aaa</div>
				</Col> */}
				<Col>
					<div className="wrapper" style={{
							backgroundColor: '#fff'
						}}>
						<BraftEditor {...editorProps} ref={instance => (this.editorInstance = instance)}/>
					</div>
				</Col>
			</Row>
			<Divider style={{
					margin: '40px 0 24px'
				}}/>
			<Row type="flex" justify="center" style={{
					marginTop: '40px'
				}}>
				<Button onClick={onPrev} style={{
						marginRight: 8
					}}>
					上一步
				</Button>
				<Button onClick={onValidateForm} loading={submitting}>下一步</Button>
			</Row>
		</div>);
	}
}

export default connect(({article, upload, loading}) => ({data: article.step, uploadAccessToken: upload.access_token, submitting: loading.effects['article/submitStepForm']}))(Step2);
